<script setup lang="ts">
import type { LoginRuleForm, CgPassRuleForm } from '@/types/login'
import type { FormInstance } from 'element-plus'
import type { FormRules } from 'element-plus/lib/components/index.js'
import { reactive, ref } from 'vue'
import { getCodeApi, loginApi, cgCodeApi, cgPasswordApi } from '@/api/login'
import JSEncrypt from 'jsencrypt'
import { Md5 } from 'ts-md5'
import { ElMessage } from 'element-plus'
import { onUnmounted } from 'vue'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
import { ordinaryApplicationArry } from './menu'

const store = useUserStore() // 用户信息
const ruleFormRef = ref<FormInstance>()
const loginLoading = ref(false)
const loginFrom = ref<any>({
  name: '',
  password: '',
  verificationCode: ''
})
if (import.meta.env.VITE_APP_DEV === 'development') {
  loginFrom.value.name = 'duanxiaolong'
  loginFrom.value.password = 'D2606685127dxl..'
}
// 加密密码
const encryptPassword = ref<any>()

const rules = reactive<FormRules<LoginRuleForm>>({
  name: [{ required: true, message: '请输入用户名/手机号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  verificationCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})

const oneShow = ref(false)
const time = ref(0)
let timeId: any
const getCode = async (info: any) => {
  await getCodeApi(info)
    .then((res: any) => {
      if (res.code === 0) {
        ElMessage({ message: res.message, type: 'success' })
        time.value = 60
        timeId = setInterval(() => {
          if (time.value <= 0) {
            clearInterval(timeId)
          } else {
            time.value--
          }
        }, 1000)
      } else {
        ElMessage({ message: res.message, type: 'error' })
      }
    })
    .catch((err) => {
      ElMessage({ message: err, type: 'error' })
    })
}

const encrypt = new JSEncrypt()
const md5 = new Md5()
const getCodeFn = () => {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  let errCount = 0
  let isAllowNest = false
  const updateAll = ['name', 'password']
  const publicKey =
    'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwjDm1HXDw8QH5ZtGMQIl2h/I8E+chOQA8aQ8xCR/+aHnROaN/ZU5Vmd2Zz7g6cAacR9BSm60+iSCYtvEGJKl0WqvbPGJkc8tedjNF1QqgWqkkuE6Udgw2OkEKJCxDg6PrAniR7Cc0io9G8bW4P8JDJjSbbafvMPDDFbVVUWJxxwIDAQAB'
  encrypt.setPublicKey(publicKey)
  updateAll.forEach((item) => {
    ruleFormRef.value?.validateField(item, async (valid) => {
      console.log(valid)
      if (valid) {
        ++errCount
        errCount === 2 ? (isAllowNest = true) : (isAllowNest = false)
        if (isAllowNest) {
          md5.appendAsciiStr(loginFrom.value.password)
          encryptPassword.value = md5.end()
          const params = {
            user_id: loginFrom.value.name,
            password: encryptPassword.value
          }
          const encryptStr = encrypt.encrypt(JSON.stringify(params))
          getCode(encryptStr)
        }
      }
    })
  })
}

const router = useRouter() // 路由
const loginFn = async (form: any) => {
  loginLoading.value = true
  await loginApi(form)
    .then((res: any) => {
      if (res.code === 0) {
        store.setPathsArry(ordinaryApplicationArry)
        store.setToken(res.message.token)
        store.setAppInfo(res.message.apps)
        store.setNavInfo(res.message.menus)
        store.setUser(res.message.sys)
        store.setReturnUrl(res.message.url)
        store.creatNavBar()
        router.push({ path: '/home' })
        ElMessage({ message: '登录成功！', type: 'success' })
      } else {
        ElMessage({ message: res.message, type: 'error' })
      }
    })
    .catch((err) => {
      ElMessage({ message: err, type: 'error' })
    })
    .finally(() => {
      loginLoading.value = false
    })
}

const submitForm = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      const params = {
        user_id: loginFrom.value.name,
        password: encryptPassword.value,
        code: loginFrom.value.verificationCode
      }
      loginFn(params)
      // console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}

const loginShow = ref(true)
const cgPassShow = ref(false)
const cgPasswordRef = ref<FormInstance>()
const cgPassword = ref<any>({
  name: '',
  verificationCode: '',
  newPass: '',
  confirmPass: ''
})
const resetCgPassword = ref<any>({
  name: '',
  verificationCode: '',
  newPass: '',
  confirmPass: ''
})
const cgOneShow = ref(false)
const cgTwoShow = ref(false)

const validatePass2 = (rule: any, value: any, callback: any) => {
  // 二次验证密码
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== cgPassword.value.newPass) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}
const cgPassRules = reactive<FormRules<CgPassRuleForm>>({
  name: [{ required: true, message: '请输入用户名/手机号', trigger: 'blur' }],
  verificationCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  newPass: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '新密码长度在 6 到 20 个字符', trigger: 'blur' },
    {
      pattern: /^\S*(?=\S{6,20})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*?.])\S*$/,
      message: '密码必须包含大小写字母、数字和特殊字符(!@#$%^&*?)',
      trigger: 'blur'
    }
  ],
  confirmPass: [{ required: true, validator: validatePass2, trigger: 'blur' }]
})
const showCgPassword = () => {
  // 这里做了对动画的处理，因为动画是异步的，所以需要延时处理
  if (loginShow.value) {
    loginShow.value = !loginShow.value
    clearInterval(timeId)
    time.value = 0
    ruleFormRef.value?.resetFields()
    setTimeout(() => {
      cgPassShow.value = !cgPassShow.value
    }, 200)
  } else {
    cgPassShow.value = !cgPassShow.value
    clearInterval(cgTimeId)
    cgTime.value = 0
    cgPasswordRef.value?.resetFields()
    setTimeout(() => {
      loginShow.value = !loginShow.value
    }, 200)
  }
}

const cgTime = ref(0)
let cgTimeId: any
const cgGetCode = () => {
  const params = {
    userId: cgPassword.value.name
  }
  cgPasswordRef.value?.validateField('name', async (valid) => {
    console.log(valid)
    if (valid) {
      await cgCodeApi(params)
        .then((res: any) => {
          if (res.code === 0) {
            ElMessage({ message: res.message, type: 'success' })
            cgTime.value = 60
            cgTimeId = setInterval(() => {
              if (cgTime.value <= 0) {
                clearInterval(cgTimeId)
              } else {
                cgTime.value--
              }
            }, 1000)
          } else {
            ElMessage({ message: res.message, type: 'error' })
          }
        })
        .catch((err) => {
          ElMessage({ message: err, type: 'error' })
        })
    }
  })
}
// const nPass = ref<any>()
const cgPasswordForm = async () => {
  if (!cgPasswordRef.value) return
  await cgPasswordRef.value.validate(async (valid, fields) => {
    if (valid) {
      // console.log('cgPasswordForm!')
      // md5.appendAsciiStr(cgPassword.value.newPass)
      // nPass.value = md5.end()
      const params = {
        user_id: cgPassword.value.name,
        npwd: cgPassword.value.newPass,
        auth_code: cgPassword.value.verificationCode
      }
      await cgPasswordApi(params)
        .then((res: any) => {
          // console.log(res)
          if (res.code === 0) {
            ElMessage({ message: '修改成功', type: 'success' })
            cgPassword.value = resetCgPassword.value
            cgPasswordRef.value?.resetFields()
            showCgPassword()
          } else {
            ElMessage({ message: res.message, type: 'error' })
          }
        })
        .catch((err) => {
          ElMessage({ message: err, type: 'error' })
        })
    } else {
      console.log('error cgPasswordForm!', fields)
    }
  })
}

onUnmounted(() => {
  clearInterval(timeId)
})
</script>

<template>
  <div class="loginBg">
    <div class="login_container">
      <div class="portal-logo">
        <img src="@/assets/images/login_Image.png" alt="" />
      </div>
      <div class="login_info">
        <h2>云网分析中心门户</h2>
        <h3>欢迎登陆</h3>
        <div class="formContent">
          <transition name="el-fade-in-linear">
            <el-form
              v-if="loginShow"
              class="ruleForm"
              ref="ruleFormRef"
              :model="loginFrom"
              :rules="rules"
            >
              <div class="labelBox">账号</div>
              <el-form-item prop="name">
                <el-input
                  v-model="loginFrom.name"
                  placeholder="请输入用户名/手机号"
                  class="input-with-select"
                >
                </el-input>
              </el-form-item>
              <div class="labelBox">密码</div>
              <el-form-item prop="password">
                <el-input
                  v-model="loginFrom.password"
                  placeholder="请输入密码"
                  class="input-with-select"
                  :type="oneShow ? 'text' : 'password'"
                >
                  <template #suffix>
                    <svg-icon
                      @click="oneShow = !oneShow"
                      color="#444444"
                      className="iconBox"
                      :iconName="oneShow ? 'icon-eye' : 'icon-eye-close'"
                    ></svg-icon>
                  </template>
                </el-input>
              </el-form-item>
              <div class="labelBox">验证码</div>
              <el-form-item prop="verificationCode" class="verificationCode">
                <el-input
                  v-model="loginFrom.verificationCode"
                  placeholder="请输入验证码"
                  class="input-with-select"
                >
                  <template #append>
                    <el-button
                      :disabled="time > 0 ? true : false"
                      @click="getCodeFn"
                      class="getCodeBtn"
                      link
                    >
                      {{ time > 0 ? `${time}秒后重新发送` : '获取短信验证码' }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
              <div style="text-align: right">
                <el-button
                  @click="showCgPassword"
                  style="padding: 0; height: auto; width: auto"
                  type="primary"
                  text
                >
                  忘记密码
                </el-button>
              </div>
              <el-form-item style="padding-top: 10px">
                <el-button
                  type="primary"
                  :loading="loginLoading"
                  style="width: 100%"
                  @click="submitForm()"
                  >登录</el-button
                >
              </el-form-item>
            </el-form>
          </transition>
          <transition name="el-fade-in-linear">
            <el-form
              v-if="cgPassShow"
              class="cgPassword"
              ref="cgPasswordRef"
              :model="cgPassword"
              :rules="cgPassRules"
            >
              <div class="labelBox">账号</div>
              <el-form-item prop="name">
                <el-input
                  v-model="cgPassword.name"
                  placeholder="请输入用户名/手机号"
                  class="input-with-select"
                >
                </el-input>
              </el-form-item>
              <div class="labelBox">验证码</div>
              <el-form-item prop="verificationCode" class="verificationCode">
                <el-input
                  v-model="cgPassword.verificationCode"
                  placeholder="请输入验证码"
                  class="input-with-select"
                >
                  <template #append>
                    <el-button @click="cgGetCode" class="getCodeBtn" link>{{
                      cgTime > 0 ? `${cgTime}秒后重新发送` : '获取短信验证码'
                    }}</el-button>
                  </template>
                </el-input>
              </el-form-item>
              <div class="labelBox">新密码</div>
              <el-form-item prop="newPass">
                <el-input
                  v-model="cgPassword.newPass"
                  placeholder="新密码"
                  class="input-with-select"
                  :type="cgOneShow ? 'text' : 'password'"
                >
                  <template #suffix>
                    <svg-icon
                      @click="cgOneShow = !cgOneShow"
                      color="#444444"
                      className="iconBox"
                      :iconName="cgOneShow ? 'icon-eye' : 'icon-eye-close'"
                    ></svg-icon>
                  </template>
                </el-input>
              </el-form-item>
              <div class="labelBox">确认密码</div>
              <el-form-item prop="confirmPass" class="verificationCode">
                <el-input
                  v-model="cgPassword.confirmPass"
                  placeholder="确认密码"
                  class="input-with-select"
                  :type="cgTwoShow ? 'text' : 'password'"
                >
                  <template #suffix>
                    <svg-icon
                      @click="cgTwoShow = !cgTwoShow"
                      color="#444444"
                      className="iconBox"
                      :iconName="cgTwoShow ? 'icon-eye' : 'icon-eye-close'"
                    ></svg-icon>
                  </template>
                </el-input>
              </el-form-item>
              <div style="text-align: right">
                <el-button
                  @click="showCgPassword"
                  style="padding: 0; height: auto; width: auto"
                  type="primary"
                  text
                >
                  返回登录
                </el-button>
              </div>
              <el-form-item style="padding-top: 10px">
                <el-button
                  type="primary"
                  :loading="loginLoading"
                  style="width: 100%"
                  @click="cgPasswordForm()"
                >
                  确认修改
                </el-button>
              </el-form-item>
            </el-form>
          </transition>
        </div>
      </div>
    </div>
    <div class="login_footer">
      @Copyright by 中国电信股份有限公司&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;新疆分公司
      <div>请使用谷歌浏览器 或 360浏览器进行浏览</div>
    </div>
  </div>
</template>

<style scoped lang="less">
.loginBg {
  position: relative;
  width: 100vw;
  height: 100vh;
  background-color: var(--cnac-text2);

  .login_container {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
    background-color: #fff;
    height: 600px;
    width: 75%;
    min-width: 1100px;
    border-radius: 20px;
    .portal-logo {
      img {
        width: 420px;
        height: 100%;
        vertical-align: middle;
      }
    }

    :deep(.login_info) {
      width: 352px;
      margin-left: 100px;
      .formContent {
        display: flex;
      }
      .labelBox {
        color: var(--cnac-text1);
        font-weight: 500;
        margin-bottom: 10px;
      }

      h2 {
        color: var(--cnac-text2);
        font-size: 30px;
        text-align: center;
        padding-top: 20px;
      }

      h3 {
        text-align: center;
        color: var(--cnac-text1);
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 30px;
      }

      .verificationCode {
        .getCodeBtn {
          width: 140px;
          // padding: 0 10px;
        }
      }

      .el-button--primary {
        height: 40px;
        width: 120px;
      }

      .ruleForm {
        .el-form-item {
          margin-bottom: 41px;
        }
      }
      .cgPassword {
        .el-form-item {
          margin-bottom: 18px;
        }
      }

      .input-with-select {
        height: 40px;
      }

      .el-input-group__prepend {
        background-color: transparent;
      }
    }
  }

  .login_footer {
    position: absolute;
    bottom: 40px;
    width: 100%;
    text-align: center;
    color: #000;
    font-size: 12px;

    span {
      margin-left: 20px;
    }
  }
}
</style>
